package com.lcc.lynx.security.interceptor;

import com.lcc.lynx.common.exception.e.UnauthorizedException;
import com.lcc.lynx.security.Session;
import com.lcc.lynx.security.ThreadVariable;
import com.lcc.lynx.security.annotation.Anonymous;
import com.lcc.lynx.security.config.SecurityProperties;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger("LoginInterceptor");

    @Autowired
    SecurityProperties securityProperties;

//    @Value("${lynx.config.interface.include}")
//    private String[] notUri;
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        ThreadVariable.localToken.remove();
        String uri = req.getServletPath();
        String ip = Session.getIpAddress(req);
        logger.info("request ip:"+ip+" uri = "+uri);

        if(handler instanceof HandlerMethod method){
            if(method.hasMethodAnnotation(Anonymous.class) || method.getBean().getClass().getAnnotation(Anonymous.class) != null){
                return true;
            }
        }

        String token = req.getHeader("token");
        if(token == null && req.getCookies() != null){
            for (Cookie cookie : req.getCookies()) {
                if(cookie.getName().equals("token")){
                    token = cookie.getValue();
                    break;
                }
            }

        }
        // 记录token
        ThreadVariable.localToken.set(token);
        // 放行不需要登录校验的路径
        for (String not : securityProperties.getPermitAll()) {
            int i = not.indexOf("*");
            if(i != -1){
                if(uri.startsWith(not.substring(0, i-1))){
                    return true;
                }
            }
            if(uri.equals(not)){
                return true;
            }
        }
        // 判断是否登录
        if(Session.getUserInfo() == null){
            throw new UnauthorizedException("登录身份过期");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        ThreadVariable.localToken.remove();
    }
}
